//
//  UserAccountViewModel.swift
//  0110-weibo
//
//  Created by 鲍志刚 on 16/1/12.
//  Copyright © 2016年 zhongye. All rights reserved.
//

import UIKit
import AFNetworking

class UserAccountViewModel: NSObject {
    

    var userAccount: UserAccount?
    
    override init() {
        userAccount = UserAccount.loadUserAccount()
        super.init()
    }
    
    //用户是否登录的标记
    //只读属性 计算型属性
    var userLogin: Bool {
        return userAccount?.access_token != nil
    }
    
    //从缓存获取token
    var token: String? {
    
        return userAccount?.access_token
    }
    
    //用户名称
    var userName: String? {
    
    return userAccount?.name
    }
    
    //用户头像url
    var headImageURL: NSURL? {
    
    return NSURL(string: userAccount?.avatar_large ?? "")
    }
    
    
    // 获取授权的token 
    func loadAccessToken (code : String, finished:(isSuccess:Bool) -> ()) {
    
    let urlString = "https://api.weibo.com/oauth2/access_token"
    let parameters = ["client_id":client_id,"client_secret": client_secret, "grant_type":"authorization_code","code": code,"redirect_uri": redirect_uri]
        let AFN = AFHTTPSessionManager()
        
        //设置支持解析纯文本的json格式的数据
    AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print(result)
            
            //类型 转换 将 anyObject对象 转换成 [Key : Value]
            guard let dict = result as?[String : AnyObject] else {
            
            print("数据格式不合法")
                
                finished(isSuccess: false)
                return
            
            }
            
            //程序走到这里 代表 anyobject 一定被转换成 字典格式的数据
            let account = UserAccount(dict: dict)
            print(account)
            
            //加载用户信息
            self.loadUserInfo(account,finished: finished)
            
            
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }

    }
    
    
    //MARK: 加载用户信息
    func loadUserInfo(account: UserAccount, finished:(isSuccess: Bool) -> ()) {
        //        print(access_token,uid)
        //准备url
        let urlString = "https://api.weibo.com/2/users/show.json"
        //OC  {"nullobject" : [NSNull null]}
        //程序员保证这个地方一定有值
        let parameters = ["access_token": account.access_token!, "uid": account.uid!]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            print(result)
            //获取用户数据
            //类型 转换 将 anyObject对象 转换为 [Key : Value]
            
            guard let dict = result as? [String : AnyObject] else {
            
                print("数据格式不合法")
                 finished(isSuccess: false)
                return
            
            }
            
            let name = dict["name"] as! String
            let avatar_large = dict["avatar_large"] as! String
            //我们需要的用户信息就全部获取到
            account.name = name
            account.avatar_large = avatar_large
            print(account)
            
            account.saveAccount()
            
            //执行成功的回调
            finished(isSuccess: true)
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }
        
        
    }

}
